window.onload = () => {
  var logger = document.querySelector('#logger')
  var startBtn = document.querySelector('#startBtn')
  
  // logger
  var logMsgs = []
  var maxMsgsLen = 10
  function pushLog(msg) {
    if (logMsgs.length > maxMsgsLen) {
      logMsgs.shift()
    }
    logMsgs.push(msg)
    showLog()
  }

  function showLog() {
    logger.value = logMsgs.join('\n')
  }
  // logger end


  // communication
  var wsComm = new WebSocket("ws://localhost:9100/commander");

  wsComm.onopen = function () {
    wsComm.send('getState')
  };

  wsComm.onmessage = function (evt) {
    let [type, msg] = evt.data.split(':::')
    if(type == 'state'){
      if(msg == 'started'){
        startBtn.innerHTML = 'stop';
        pushLog('started');
      } else {
        startBtn.innerHTML = 'start';
        pushLog('stop');
      }
    } else if(type == 'log'){
      pushLog(msg);
    }
  };

  wsComm.onclose = function () {
	  alert('connction is losing')
  };
  // communication end
  
  startBtn.onclick = ()=>{
    wsComm.send('toogle');
  }
}
